package com.summer.data.table.column;

import com.summer.data.logging.Logger;
import com.summer.data.logging.LoggerFactory;
import com.summer.data.table.BaseColumn;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 日期：年月日，不带时间
 * 
 * @author 345480567@qq.com
 */
public class DateColumn extends BaseColumn<LocalDate> {

    private static Logger logger = LoggerFactory.getLogger(DateColumn.class);

    public DateColumn(String colName) {
        super(colName);
    }

    @Override
    public void fetchNotNullValue(ResultSet resultSet, Integer index) throws SQLException {
        value = getValue(resultSet, index);
    }

    public void generateWithCurrent() {
        setValue(LocalDate.now());
    }

    public static LocalDate getValue(ResultSet resultSet, Integer index) throws SQLException {
        Object object = resultSet.getObject(index);
        LocalDate value = null;
        if (object != null) {
            if (object instanceof LocalDate) {
                value = (LocalDate) object;
            } else if (object instanceof LocalDateTime) {
                logger.warn("时间类型不匹配: db:%s  -> java:%s", new Object[] {
                        object.getClass().getName(),
                        LocalTime.class.getName()
                });
                LocalDateTime localDateTime = (LocalDateTime) object;
                value = localDateTime.toLocalDate();
            } else if (object instanceof java.sql.Date) {
                java.sql.Date date = (java.sql.Date) object;
                value = date.toLocalDate();
            } else {
                logger.warn("时间类型不匹配: db:%s  -> java:%s", new Object[] {
                        object.getClass().getName(), LocalTime.class.getName()
                });
            }
        }

        return value;
    }

}
